const crypto = require('crypto');
module.exports = {
	// api格式统一
	Success(data = '', msg = 'ok', code = 200) {
		this.body = { msg, data };
		this.status = code;
	},
	Fail(data = '', msg = 'fail', code = 400) {
		this.body = { msg, data };
		this.status = code;
	},

	async getToken(value) {
		return this.app.jwt.sign(value, this.app.config.jwt.secret);
	},
	async checkToken(token) {
		return this.app.jwt.verify(token, this.app.config.jwt.secret);
	},
	// 加密
	async createPassword(password) {
		const hmac = crypto.createHash('sha256', this.app.config.crypto.secret);
		hmac.update(password);
		return hmac.digest('hex');
	},
	// 验证密码
	async checkPassword(password, hash_password) {
		password = await this.createPassword(password);
		return password === hash_password;
	},
	// 生成唯一id
	genID(length) {
		return Number(
			Math.random().toString().substr(10, length) + Date.now()
		).toString(36);
	},
	// 判断移动端还是pc端
	ismobile(ctx) {
		let userAgent = this.request.header['user-agent'].toLowerCase();
		let pat_phone =
			/ipad|iphone os|midp|rv:1.2.3.4|ucweb|android|windows ce|windows mobile/;
		return pat_phone.test(userAgent);
	}
};
